package com.tencent.txcc.mq.consumer;

import com.tencent.txcc.domain.PayOrder;
import com.tencent.txcc.enums.GlobleExceptionCode;
import com.tencent.txcc.service.IAlipayInfoService;
import com.tencent.txcc.service.IPayOrderService;
import com.tencent.txcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "course-pay-handler-delay-group",
        topic = "course-order-handler-delay-topic",
        selectorExpression = "course-order-handler-delay-tag",
        messageModel = MessageModel.BROADCASTING
)
public class CoursePayHandlerDelayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    /**
     * 消费者有一个签收模式：
     *  什么都不返回：签收成功
     *  报错了：签收失败，重新发送
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.业务校验
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotEmpty(orderNo, GlobleExceptionCode.ERROR);
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);

        if (payOrder == null){
            return;
        }
        if (PayOrder.WAIT_PAY_STATUS.equals(payOrder.getPayStatus())){
            try {
                payOrderService.cancelOrder(orderNo, payOrder);
            } catch (Exception e) {
                log.error("订单关闭失败，订单号为：{}", orderNo);
                e.printStackTrace();
            }
        }

    }
}